import { BrowserWindow, app, shell } from 'electron';
import icon from '../../resources/icon.png?asset'
import { join } from 'path'
import { is } from '@electron-toolkit/utils'

let jingWin = null;

const createjingWin = () => {
    jingWin = new BrowserWindow({
        title: 'Yangshao 井字棋',
        width: 400,
        height: 430,
        autoHideMenuBar: true,
        icon: icon,
        webPreferences: {
            nodeIntegration: true,
            preload: join(__dirname, '../preload/index.js'),
        },
        resizable: false,
        show:false

    });
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
        jingWin.loadURL(process.env['ELECTRON_RENDERER_URL'])
    } else {
        jingWin.loadFile(join(__dirname, '../renderer/index.html'))
    }
    // 假设你想在创建窗口后立即打开设置路由
    jingWin.webContents.on('did-finish-load', () => {
        jingWin.webContents.send('set-route', '/jing');
    });

    jingWin.webContents.setWindowOpenHandler((details) => {
        if (url.startsWith('https:')) shell.openExternal(url);
        return { action: 'deny' }
    })

    return jingWin;
}
function closejingWin() {
    if (jingWin && !jingWin?.isDestroyed()) {
        jingWin?.close();
    }
    jingWin = null;
}

function openjingWin() {
    if (!jingWin || jingWin?.isDestroyed()) {
        jingWin = createjingWin();
    }
}
function showjingWin(){
    jingWin?.show();
}
function hidejingWin() {
    jingWin.hide();
}
// 写一个show和hide切换
function showHidejingWin() {
    jingWin.isVisible() ? jingWin.hide() : jingWin.show();
}
function goHomejingWin() {
    jingWin.loadURL('http://localhost:3456/jing')
}

function minimizejingWin() {
    jingWin.minimize();
}

function focusjingWin() {
    if (!jingWin || jingWin?.isDestroyed()) {
        jingWin = createjingWin();
    } else {
        // Focus on the main window if the user tried to open another
        if (jingWin.isMinimized()) jingWin.restore();
        if (!jingWin.isVisible()) jingWin.show();
        jingWin.focus();
    }
}

function sendEuUpdateCanAvailable(arg, update) {
    if (jingWin && !jingWin?.isDestroyed()) {
        jingWin.webContents.send('eu:update-can-available', {
            update: update,
            version: app.getVersion(),
            newVersion: arg?.version,
        });
    }
}

export {
    closejingWin,
    createjingWin,
    showjingWin,
    focusjingWin,
    hidejingWin,
    minimizejingWin,
    openjingWin,
    sendEuUpdateCanAvailable,
    showHidejingWin,
    goHomejingWin
};